package com.gm.wholesale.module.voice.voiceCreateOrder;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.ArrayMap;

import androidx.annotation.NonNull;

import com.gm.commonlib.base.baseBean.BaseListResp;
import com.gm.commonlib.base.baseBean.DataResp;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.util.logUtils.LogUtil;
import com.gm.commonlib.views.popupwindow.Popupwindow;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.bluetooth.bean.WeightBean;
import com.gm.wholesale.cacheData.CacheData;
import com.gm.wholesale.constant.Constant;
import com.gm.wholesale.constant.Unit;
import com.gm.wholesale.module.custom.ChoiceCustomData;
import com.gm.wholesale.module.custom.bean.CustomBean;
import com.gm.wholesale.module.good.bean.GoodBean;
import com.gm.wholesale.module.good.model.GoodModel;
import com.gm.wholesale.module.order.bean.OrderRecmPriceBean;
import com.gm.wholesale.module.order.model.OrderModel;
import com.gm.wholesale.module.voice.IVoiceListener;
import com.gm.wholesale.module.voice.VoiceManger;
import com.gm.wholesale.module.voice.bean.VoiceGetGoodBean;
import com.gm.wholesale.module.voice.model.VoiceModel;
import com.gm.wholesale.util.Utils;

public class VoiceCreateOrderManger {

    private static VoiceCreateOrderManger manger;

    public static VoiceCreateOrderManger newInstance() {
        if (manger == null) {
            manger = new VoiceCreateOrderManger();
        }
        return manger;
    }

    public interface OnVoiceCreateOrderListener {
        void createOrder(GoodBean goodBean);

        void showCreateOrderView(GoodBean goodBean);

        void onStart();

        void onTimelyData(String data);

    }


    private WeightBean mWeightBean;

    private GoodBean mGood;


    public void setWeightBean(WeightBean weightBean) {
        mWeightBean = weightBean;
    }

    //todo 根据语音去商品库查询商品
    private void getGoodByVoice(String goodName, OnVoiceCreateOrderListener listener) {
        mGood = null;
        mGood = new GoodBean();
        mGood.setName(goodName);
        LogUtil.d("调用接口解析数据");
        ArrayMap<String, Object> queryData = new ArrayMap<>();
        queryData.put("text", goodName);
        VoiceModel.getGoodByVoice(null, queryData, new BaseHttpObserver<DataResp<VoiceGetGoodBean>>() {
            @Override
            protected void handleResultOkResp(DataResp<VoiceGetGoodBean> resp) {
                if (resp == null || resp.getData() == null
                        || resp.getData().getItems() == null
                        || resp.getData().getItems().isEmpty()) {
                    //有重量的话，才去数据库获取商品信息和价格，不然直接跳创建订单界面
                    //没有重量，必定跳创建订单界面去，那个界面会通过名字掉接口查询商品
                    //这里就没有必要重复查询了
                    if (mWeightBean != null && mWeightBean.getWeightNum() > 0) {
                        getGoodByName(goodName, listener);
                    } else {
                        LogUtil.d("onResult: 接口返回数据成功1");
                        createOrder(listener);
                    }

                } else {
                    LogUtil.d("onResult: 接口返回数据成功2");
                    //todo 接口解析出数据，创建订单
                    createOrderByFindGood(resp.getData().getItems().get(0), listener);
                }
            }

            @Override
            protected void handleResultOtherResp(DataResp<VoiceGetGoodBean> resp) {
                if (mWeightBean != null && mWeightBean.getWeightNum() > 0) {
                    getGoodByName(goodName, listener);
                } else {
                    createOrder(listener);
                }
            }

            @Override
            protected void onError(String error) {
                if (mWeightBean != null && mWeightBean.getWeightNum() > 0) {
                    getGoodByName(goodName, listener);
                } else {
                    createOrder(listener);
                }
            }
        });
    }

    // todo 通过语音调用接口解析数据，没有解析出来，则通过名字查询商品详情
    private void getGoodByName(String goodName, OnVoiceCreateOrderListener listener) {
        ArrayMap<String, Object> queryData = new ArrayMap<>();
        queryData.put("name", goodName);
        GoodModel.getSearchGood(null, queryData, new BaseHttpObserver<BaseListResp<GoodBean>>() {
            @Override
            protected void handleResultOkResp(BaseListResp<GoodBean> resp) {
                if (resp.getDatas() != null && !resp.getDatas().isEmpty()) {
                    //todo 设置里面关闭填入价格得话，把商品里面价格置空（查询商品时候，商品默认带有价格，需要移除）
                    mGood = resp.getDatas().get(0);
                    if (!CacheData.getIsAutoInputPrice()) {
                        mGood.setPrice(0);
                    } else {
                        //获取斤单位的价格，填入
                        mGood.setPrice(mGood.getPriceByJin());
                    }
                } else {
                    mGood.setPrice(0);
                }
            }

            @Override
            public void onComplete() {
                super.onComplete();
                //todo 用戶打開自動录入价格才去获取价格
                if (mGood.getId() > 0 && CacheData.getIsAutoInputPrice()) {
                    getGoodPrice(mGood.getId(), listener);
                } else {
                    if (listener != null) {
                        createOrder(listener);
                    }
                }

            }
        });
    }


    private void getGoodPrice(long goodId, OnVoiceCreateOrderListener listener) {
        CustomBean customBean = ChoiceCustomData.newInstance().getCustomBean();
        ArrayMap<String, Object> queryData = new ArrayMap<>();
        if (customBean != null) {
            queryData.put("customerID", customBean.getId());
            queryData.put("skuID", goodId);
            OrderModel.getOrderRecPrice(null, queryData, new BaseHttpObserver<>() {
                @Override
                protected void handleResultOkResp(DataResp<OrderRecmPriceBean> resp) {
                    if (resp != null && resp.getData() != null) {
                        setGoodPrice(resp.getData());
                    }
                }

                @Override
                public void onComplete() {
                    if (listener != null) {
                        createOrder(listener);
                    }
                }
            });
        }
    }

    private void setGoodPrice(OrderRecmPriceBean orderRecPriceBean) {
        double price = Utils.getOrderRecmPrice(orderRecPriceBean);
        if (mGood != null && price > 0 && CacheData.getIsAutoInputPrice()) {
            mGood.setPrice(price);
        }
    }


    //todo 在后端获取到数据
    private void createOrderByFindGood(VoiceGetGoodBean.ItemsDTO good, OnVoiceCreateOrderListener listener) {
        LogUtil.d("onResult: createOrderByFindGood");
        if (good != null) {
            mGood = new GoodBean();
            mGood.setIsVoiceCreate(true);
            mGood.setId(good.getSkuId());
            mGood.setName(good.getSkuName());
            //货物单位
            if (!TextUtils.isEmpty(good.getUnitName())) {
                mGood.setUnitName(good.getUnitName());
            } else {
                mGood.setUnitName(Constant.DEFAULT_UNIT);
            }
            //获取价格
            if (!TextUtils.isEmpty(good.getUnitPrice())) {
                double price = Double.parseDouble(good.getUnitPrice());
                if (price > 0) {
                    mGood.setPrice(price);
                } else {
                    mGood.setPrice(0);
                }
            } else {
                mGood.setPrice(0);
            }
            //货物数量
            if (!TextUtils.isEmpty(good.getQuantity()) && Double.parseDouble(good.getQuantity()) > 0) {
                mGood.setGoodNum(Double.parseDouble(good.getQuantity()));
            } else {
                if (mWeightBean != null && mWeightBean.getWeightNum() > 0) {
                    double num = Unit.getWeight(mWeightBean.getsUnit(), mGood.getUnitName(), mWeightBean.getWeightNum());
                    mGood.setGoodNum(num);
                }
            }
        }
        if (mGood.getGoodNum() > 0) { //直接创建单子
            if (listener == null) return;
            listener.createOrder(mGood);
        } else { //到创建订单界面，用户可以修改单子
            LogUtil.d("跳转界面创建111");
            if (listener == null) return;
            listener.showCreateOrderView(mGood);
        }
        //停止录音
        stop();


    }


    //todo 异常或者接口没有 找到数据，直接使用语音解析的文字的创建订单
    private void createOrder(OnVoiceCreateOrderListener listener) {
        LogUtil.d("onResult createOrdercreateOrder: ");
        mGood.setIsVoiceCreate(true);
        if (listener == null) {
            LogUtil.d("onResult mListener =null");
            stop();
            return;
        }
        //商品没有重量，到创建订单页面
        if (mWeightBean == null || mWeightBean.getWeightNum() <= 0) {
            LogUtil.d("跳转界面创建4444");
            listener.showCreateOrderView(mGood);
        } else {
            // todo 语音录单默认使用斤
            mGood.setUnitName(Constant.DEFAULT_UNIT);
            double num = Unit.getWeight(mWeightBean.getsUnit(), Constant.DEFAULT_UNIT, mWeightBean.getWeightNum());
            mGood.setGoodNum(num);

            listener.createOrder(mGood);
            mWeightBean = null;
        }
        stop();


    }

    public void start(Context context, OnVoiceCreateOrderListener listener) {
        mGood = null;
        VoiceManger.getVoiceManger().startVoice(context, new IVoiceListener() {
            @Override
            public void onVolumeChanged() {

            }

            @Override
            public void onEndOfSpeech() {

            }

            @Override
            public void onResult(String text) {
                LogUtil.d("onResult: 科大讯飞获取数据返回");
                if (!TextUtils.isEmpty(text)) {

                    getGoodByVoice(text, listener);
                }

            }

            @Override
            public void onError(String error) {
                stop();
                ToastUtil.showToast(error);
                Popupwindow.hiddenPop();

            }

            @Override
            public void onTimelyData(String data) {
                listener.onTimelyData(data);
            }

            @Override
            public void onBeginOfSpeech() {
                if (listener!=null){
                    listener.onStart();
                }

            }
        });
    }


    public void stop() {
        VoiceManger.getVoiceManger().stop();
        LogUtil.d("onResult stop");
        mWeightBean = null;
        manger = null;

    }




}
